package com.tg.paw.ums.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tg.paw.common.enums.StatusEnum;
import com.tg.paw.ums.dto.*;
import com.tg.paw.ums.entity.Admin;
import com.tg.paw.ums.entity.Permission;
import com.tg.paw.ums.entity.Role;
import com.tg.paw.ums.entity.RolePermissionRelation;
import com.tg.paw.ums.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdminUserServiceImpl  implements IAdminUserService {

    @Autowired
    private IAdminService adminService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IRolePermissionRelationService rolePermissionRelationService;

    private final String ADMIN = "admin";


    @Override
    public UserInfoDto getAdminInfo(String username) {
        UserInfoDto userInfoDto = new UserInfoDto();
        Admin entity = new Admin();
        entity.setAdminName(username);
        Admin admin = adminService.getOne(new QueryWrapper<>(entity));
        if(admin==null){
            return userInfoDto;
        }
        convert(admin,userInfoDto);

        // 角色
        if(ADMIN.equals(username)){
            admin.setRoleId(1L);
            admin.setRoleName("admin");
            RoleDto roleDto = new RoleDto();
            roleDto.setId("1");
            roleDto.setName("admin");
            roleDto.setDescribe("系统管理员");
            userInfoDto.setRole(roleDto);
        }else {
            long roleId = admin.getRoleId();
            Role role = roleService.getById(roleId);
            if(role==null || role.getStatus()== StatusEnum.OFF.getValue()){
                return userInfoDto;
            }
            convert(role,userInfoDto);
        }

        // 权限
        List<Permission> permissions = null;
        if(ADMIN.equals(username)){
            // 获取所有权限
            permissions = permissionService.list();
        }else {
            permissions = getRolePermissions(admin.getRoleId());
        }

        convert(permissions,userInfoDto);

        return userInfoDto;
    }

    @Override
    public List<NavigatorMenu> getAdminNavigator(String username) {

        // 权限
        List<Permission> permissions = null;
        if(ADMIN.equals(username)){
            // 获取所有权限
            permissions = permissionService.list();
        }else {
            Admin entity = new Admin();
            entity.setAdminName(username);
            Admin admin = adminService.getOne(new QueryWrapper<>(entity));
            permissions = getRolePermissions(admin.getRoleId());
        }
        // 去除按钮
        permissions = permissions.stream().filter(item->item.getPermissionType()!=2).collect(Collectors.toList());

        return null;
    }


    /**
     * 获取角色权限
     * @param roleId
     * @return
     */
    private List<Permission> getRolePermissions(Long roleId){
        RolePermissionRelation rolePermissionRelation = new RolePermissionRelation();
        rolePermissionRelation.setRoleId(roleId);
        QueryWrapper<RolePermissionRelation> rolePermissionRelationQueryWrapper = new QueryWrapper<>(rolePermissionRelation);
        List<RolePermissionRelation> rolePermissionRelations = rolePermissionRelationService.list(rolePermissionRelationQueryWrapper);

        // 查询分配的启用权限
        List<Long> permissionIds = rolePermissionRelations.stream().map(RolePermissionRelation::getPermissionId).collect(Collectors.toList());
        LambdaQueryWrapper<Permission> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Permission::getPermissionId,permissionIds);
        lambdaQueryWrapper.eq(Permission::getStatus, StatusEnum.ON.getValue());
        List<Permission> permissionList = permissionService.list(lambdaQueryWrapper);
        List<Permission> menuPermissionList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(permissionList)){
            // 查询权限的 菜单目录树
            List<Permission> allPermission = permissionService.list();
            Map<Long,Permission> permissionMap = new HashMap<>(allPermission.size());
            for (Permission permission:
                 allPermission) {
                permissionMap.put(permission.getPermissionId(),permission);
            }
            for (Permission permission :
                    permissionList) {
                getParentPermission(permission, permissionMap, menuPermissionList);
            }

            permissionList.addAll(menuPermissionList);
        }

        return  permissionList;
    }

    private void getParentPermission(Permission permission,Map<Long,Permission> permissionMap,List<Permission> permissionList){
        if(permission==null || permission.getParentId()==0L){
            return;
        }
        Permission parent = permissionMap.get(permission.getParentId());
        if(parent!=null){
            permissionList.add(parent);
            if(parent.getParentId()!=0L){
                getParentPermission(parent,permissionMap,permissionList);
            }
        }
    }

    /**
     * 用户信息
     * @param admin
     * @param userInfoDto
     */
    private void convert(Admin admin,UserInfoDto userInfoDto){
        userInfoDto.setRoleId(String.valueOf(admin.getRoleId()));
        userInfoDto.setCreatorId(admin.getCreator());
        userInfoDto.setTelephone(admin.getPhone());
        userInfoDto.setAvatar(admin.getAvatar());
        userInfoDto.setCreateTime(admin.getCreateTime());
        userInfoDto.setName(admin.getAdminName());
        userInfoDto.setId(String.valueOf(admin.getAdminId()));
        userInfoDto.setStatus(admin.getStatus());
        userInfoDto.setLastLoginTime(admin.getLoginTime());
    }

    /**
     * 角色
     * @param role
     * @param userInfoDto
     */
    private void convert(Role role,UserInfoDto userInfoDto){
        RoleDto roleDto = new RoleDto();
        roleDto.setId(String.valueOf(role.getRoleId()));
        roleDto.setName(role.getRoleName());
        roleDto.setDescribe(role.getDescription());
        roleDto.setStatus(role.getStatus());

        userInfoDto.setRole(roleDto);
    }

    /**
     * 权限
     * @param permissions
     * @param userInfoDto
     */
    private void convert(List<Permission> permissions,UserInfoDto userInfoDto){
//        RoleDto roleDto = userInfoDto.getRole();
//
//        List<Permission> menuPermissionList = permissions.stream().filter(item -> item.getPermissionType() != 2).collect(Collectors.toList());
//        List<PermissionsItem> permissionsItemList = new ArrayList<>();
//        for (Permission permission :
//                menuPermissionList) {
//            PermissionsItem permissionsItem = new PermissionsItem();
//            permissionsItem.setPermissionId(String.valueOf(permission.getPermissionId()));
//            permissionsItem.setRoleId(roleDto.getId());
//            permissionsItem.setPermissionName(permission.getPermissionName());
//            permissionsItem.setPermissionValue(permission.getAuthority());
//            List<Permission> actionPermissions = permissions.stream()
//                    .filter(item -> item.getParentId().equals(permission.getPermissionId()) && item.getType() == 2)
//                    .collect(Collectors.toList());
//            List<ActionEntitySetItem> actionEntitySetItems = new ArrayList<>();
//            for (Permission item :
//                    actionPermissions) {
//                ActionEntitySetItem actionEntitySetItem = new ActionEntitySetItem();
//                actionEntitySetItem.setAction(item.getPermissionValue());
//                actionEntitySetItem.setDescribe(item.getPermissionName());
//                actionEntitySetItem.setDefaultCheck(false);
//
//                actionEntitySetItems.add(actionEntitySetItem);
//            }
//            permissionsItem.setActionEntitySet(actionEntitySetItems);
//            permissionsItem.setActions(JSON.toJSONString(actionEntitySetItems));
//
//            permissionsItemList.add(permissionsItem);
//        }
//
//        roleDto.setPermissions(permissionsItemList);
    }
}
